package com.aispeech.task.etcd;

import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

@Slf4j
public class EtcdEnvironmentPostProcessor implements EnvironmentPostProcessor {
    private static final String ETCD_CONFIG_IDENTIFYER = "ETCD_CONFIG_IDENTIFYER";

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment env, SpringApplication application) {
        Properties properties = readPropertiesByEnvironment();

        if (properties != null) {
            Map<String, Object> map = new HashMap<>();

            Iterator iterator = properties.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> entry = (Map.Entry<String, String>) iterator.next();

                String key = entry.getKey();
                String value = entry.getValue();

                map.put(key, value);
            }

            MapPropertySource mapPropertySource = new MapPropertySource(ETCD_CONFIG_IDENTIFYER, map);
            env.getPropertySources().addLast(mapPropertySource);
        }

    }

    private Properties readPropertiesByEnvironment() {
        Properties properties = null;

        String etcdServerLists = System.getenv("ETCD_SERVER_INTERNAL");

        if (!StringUtils.isBlank(etcdServerLists)) {
            try {
                properties = EtcdConfigClient.loadEtcdConfig(etcdServerLists);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }

            if (properties == null)
                throw new RuntimeException(String.format("Failed read Etcd config from: %s", etcdServerLists));
        }

        return properties;
    }
}
